"use strict"
//查封列表
const cosjs = require("cosjs");
const mvc = require("cosjs.mvc");
const cosjs_redis = mvc.library.require('redis').hash;

exports.page = async function () {
    let sid = this.get('sid', 'int')
    let $page = this.get('page', 'int') || 1;
    let $size = this.get('size', 'int') || 20;
    let body = this.req.body;

    let model = mvc.model.mongo('block', sid);

    let query = {}
    let dbsort = {
        time: -1
    };
    let option = {}
    return model.page(query, $page, $size, dbsort, option);
}

exports.save = async function () {
    let data = this.req.body;
    let sid = this.get('sid', 'int')
    if (data.act == 'add') {
        let roleModel = mvc.model.mongo('role', sid);
        let _ret = await roleModel.find({ '_id': data.uid });
        if (!_ret) {
            return 'fail';
        }
        roleModel.update({ '_id': data.uid }, { '$set': { 'state': 404 } }, { "upsert": true });
        let model = mvc.model.mongo('block', sid);
        let _que = { 'uid': data.uid, 'desc': data.desc, 'msg': data.msg };

        /////////////踢下线///////////////
        await kick(sid, _ret.guid)
        /////////////踢下线///////////////

        _que.name = _ret.name;
        _que.time = Date.now();
        return model.insert(_que);
    } else if (data.act == 'del') {
        let model = mvc.model.mongo('block', sid);
        let _block_ret = await model.find({ '_id': data.id });
        if (!_block_ret) {
            return 'fail';
        }
        let roleModel = mvc.model.mongo('role', sid);
        let _ret = await roleModel.find({ '_id': _block_ret.uid });
        if (_ret) {
            roleModel.update({ '_id': _block_ret.uid }, { '$set': { 'state': 0 } }, { "upsert": true });
        }
        return model.remove({ '_id': data.id });
    }
}

exports.kickout = async function () {
    let guid = this.get('guid', 'guid')
    return await kick(this.sid, guid)
}

async function kick(sid, guid) {
    let session = mvc.config.get('session')
    let key = ["cache", sid].join("");
    let redis = cosjs.pool.get(key);
    let sessionRedis = new cosjs_redis(redis, session.prefix)
    let r = await sessionRedis.del(guid)
    return r
}
